<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'

import { useGetRoleInfo, useGetRoleMenuTreeSelect, useRoleAddOrUpdate } from '@fl/api/purchase'
import { SubmitBtn } from '@fl/components'

const props = defineProps<{ formType: 'add' | 'edit', id: string }>()

const { meta: { isAdmin } } = useRoute()

const id = defineModel<string>('id')
const visible = defineModel<boolean>('visible', { required: true })

const formRef = ref()
const { formType } = toRefs(props)

const { data: roleOptions, isLoading: TreeSelectLoading } = useGetRoleMenuTreeSelect(!!isAdmin)
const { data: roleInfo, isLoading: RoleInfoLoading } = useGetRoleInfo(id, !!isAdmin)
const { isPending, mutate } = useRoleAddOrUpdate(!!isAdmin)
const isLoading = computed(() => {
    return TreeSelectLoading.value || RoleInfoLoading.value
})
const checkStrictly = ref(false)
const cascaderProps = ref({ checkStrictly, emitPath: true, label: 'menuName', multiple: true, value: 'menuId' })
const cascaderOpitons = computed(() => {
    return roleOptions.value ? toRaw(roleOptions.value) : []
})

const formValues = ref({
    menuIds: [],
    roleDesc: '',
    roleName: '',
})

watchEffect(() => {
    if (roleInfo.value)
        formValues.value = Object.assign({}, { menuIds: roleInfo.value.menuIds, roleDesc: roleInfo.value.remark, roleName: roleInfo.value.roleName })
})

const columns: PlusColumn[] = [
    {
        label: '角色名称',
        prop: 'roleName',
        width: 120,
    },
    {
        label: '角色描述',
        prop: 'roleDesc',
        width: 120,
    },
    {
        label: '角色权限',
        prop: 'menuIds',
    },
]

const dialog = computed(() => {
    return id?.value
        ? '编辑角色'
        : '新建角色'
})
const rules = {
    menuIds: [
        {
            message: '请选择角色权限',
            required: true,
        },
    ],
    roleName: [
        {
            message: '请输入角色名称',
            required: true,
        },
    ],
}

async function confirm() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        const params = formType.value === 'add'
            ? { ...unref(formValues), menuIds: [...new Set(formValues.value.menuIds.flat())] }
            : { roleId: id?.value, ...unref(formValues), menuIds: [...new Set(formValues.value.menuIds.flat())] }
        mutate(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                cancel()
            },
        })
    }
}

function cancel() {
    visible.value = false
}

function reset() {
    id.value = ''
    formRef.value.formInstance.resetFields()
}
</script>

<template>
    <PlusDialog v-model="visible"
                :title="dialog"
                width="800"
                close-on-press-escape
                @cancel="cancel"
                @closed="reset"
    >
        <ElSkeleton v-if="isLoading"
                    animated
        />

        <PlusForm v-else
                  ref="formRef"
                  v-model="formValues"
                  :columns="columns"
                  :label-width="100"
                  :rules="rules"
                  :has-footer="false"
        >
            <template #plus-field-menuIds>
                <el-checkbox v-model="checkStrictly"
                             label="父子不联动"
                             size="large"
                />

                <el-cascader v-model="formValues.menuIds"
                             :options="cascaderOpitons"
                             :props="cascaderProps"
                             clearable
                             filterable
                             :show-all-levels="false"
                             class="w-full"
                             placeholder="请选择角色权限"
                />
            </template>
        </PlusForm>

        <template #footer>
            <div class="mx-auto">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isPending"
                           @click="confirm"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
